package com.example.myapplication.asyncTaskDemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.myapplication.R;

public class AsyncTaskDemoActivity extends AppCompatActivity implements View.OnClickListener{
    Button btn;
    ProgressBar progressBar;
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task_demo);
        txt = findViewById(R.id.async_txt);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(this);
        progressBar = findViewById(R.id.progress);
    }

    @Override
    public void onClick(View v) {
       TimeTickLoad timeTickLoad = new TimeTickLoad();
       timeTickLoad.execute(1000);
    }

    class TimeTickLoad extends AsyncTask<Integer,Integer,String>{
        @Override
        protected void onPreExecute() {
            Log.i("TAG", "onPreExecute: ");
            txt.setText("onPreExecute");
            progressBar.setVisibility(ProgressBar.VISIBLE);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            Log.i("TAG", "onPostExecute: --------"+s);
            txt.setText(s);
            super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i("TAG", "onProgressUpdate: ");
            txt.setText("onProgressUpdate");
            progressBar.setProgress(values[0]);
            super.onProgressUpdate(values);
        }

        @Override
        protected String doInBackground(Integer... integers) {
            Log.i("TAG", "doInBackground: ");
             //耗时操作，无法不可更改ui
            txt.setText("doInBackground");
            for(int i=0;i<=10;i++){
                publishProgress(i*10);
                try {
                    Thread.sleep(integers[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "执行完毕";
        }
    }

}